package com.huateng.springcloud.thread;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author Evan
 * @create 2021/7/27 14:31
 */
public class ForkJoinPoolTest {

    public static void main(String[] args) throws Exception {
        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Integer> task = pool.submit(new MyTask(1, 100));
        Integer sum = task.get();
        System.out.println("1:" + sum);
    }

}

class MyTask extends RecursiveTask<Integer>{

    //当前任务计算的开始
    private int start;
    //当前任务计算的结束
    private int end;
    //阈值，如果在end-start的阈值内，则不用在细分任务
    public static final int threshold = 2;

    public MyTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;

        boolean needFork = (end - start) > threshold;

        if (needFork){
            int middle = (start + end) / 2;
            MyTask leftTask = new MyTask(start, middle);
            MyTask rightTask = new MyTask(middle + 1, end);

            leftTask.fork();
            rightTask.fork();

            Integer leftResult = leftTask.join();
            Integer rightResult = rightTask.join();

            sum = leftResult + rightResult;
        } else {
            for (int i = start; i <= end; i++){
                sum += i;
            }
        }
        System.out.println(start + ":" + end + ":" + sum);
        return sum;
    }

}
